package com.school_admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.school_admin.config.Result;
import com.school_admin.entity.Category;
import com.school_admin.entity.Post;
import com.school_admin.mapper.MessageMapper;
import com.school_admin.mapper.PostMapper;
import com.school_admin.service.impl.CategoryServiceImpl;
import com.school_admin.service.impl.CollectionServiceImpl;
import com.school_admin.service.impl.PostServiceImpl;
import com.school_admin.util.CreateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author
 * @since 2024-03-18
 */
@RestController
@RequestMapping("/post")
public class PostController {
    private final PostServiceImpl postService;
    private final CreateTime createTime;
    private final PostMapper postMapper;
    private final MessageMapper messageMapper;
    private final CategoryServiceImpl categoryService;

    @Autowired
    public PostController(PostServiceImpl postService, CreateTime createTime,
                          PostMapper postMapper, MessageMapper messageMapper,
                          CategoryServiceImpl categoryService) {
        this.postService = postService;
        this.createTime = createTime;
        this.postMapper = postMapper;
        this.messageMapper = messageMapper;
        this.categoryService = categoryService;
    }

    // 增删改查
    @PostMapping("create")
    public Result<?> createPost(Post post) {
        /*
          TODO 1. 创建发布时间
          TODO 2. 创建发布帖子
          TODO 3. 判断是否保存成功
          TODO 4. 返回结果
         */
        post.setTime(createTime.getTime());
        boolean is = postService.save(post);
        if (is) {
            Category category = new Category();
            category.setCategoryId(post.getCategoryId());
            category.setNum(category.getNum() + 1);
            return Result.success("发表帖子成功");
        } else {
            return Result.fail("发表帖子失败");
        }
    }

    // 删除帖子
    @DeleteMapping("delete/{postId}")
    public Result<String> deletePost(@PathVariable String postId) {
        boolean is = postService.removeById(postId);
        if (is)
            return Result.success("删除帖子成功");
        return Result.fail("删除帖子失败");
    }

    @PutMapping("update")
    public Result<?> updatePost(Post post) {
        System.out.println("post = " + post);
        boolean is = postService.updateById(post);
        if (is) {
            return Result.success("更新帖子成功");
        } else {
            return Result.fail("更新帖子失败");
        }
    }

    @GetMapping("find/{postId}")
    public Result<?> findPost(@PathVariable String postId) {
        return postService.queryPost(postId);
    }

    @GetMapping("getPageListWeb")
    public Result<?> getPageListWeb(int page, int pageSize, String uid) {
        return postService.getPostListWeb(page, pageSize, uid);
    }

    // TODO 管理系统获取帖子列表
    @GetMapping("getPageListAdmin")
    public Result<?> getPageListAdmin(int page, int pageSize, String keyWord) {
        if (keyWord == null || keyWord.equals("")) {
            keyWord = "";
            return postService.getPostListAdmin(page, pageSize);
        }
        // 搜索帖子内容
        return postService.getPostListAdminSearch(page, pageSize, keyWord);
    }

    @PutMapping("updateViewCount/{postId}")
    public void updateViewCount(@PathVariable String postId) {
        postMapper.updateViewCount(postId);
    }

    @GetMapping("getNewList")
    public Result<?> getNewList() {
        List<Post> list = postMapper.getNewList();
        return Result.success(list);
    }

    @GetMapping("getSearchList")
    public Result<?> getSearchList(String value, int page, int pageSize, String type) {
        if (Objects.equals(type, "S")) {
            int start = (page - 1) * pageSize;
            List<Map<String, Object>> list = postMapper.getSearchList(value, start, pageSize);
            if (list.size() >= 1) {
                Map<String, Object> map = new HashMap<>();
                map.put("list", list);
                map.put("total", postMapper.getSearchListCount(value));
                return Result.success(map);
            }
        } else {
            int start = (page - 1) * pageSize;
            List<Map<String, Object>> list = postMapper.getSearchListForTag(value, start, pageSize);
            if (list.size() >= 1) {
                Map<String, Object> map = new HashMap<>();
                map.put("list", list);
                map.put("total", postMapper.getSearchListForTagCount(value));
                return Result.success(map);
            }
        }
        return Result.fail("搜索内容为空");
    }

    // 帖子设置私密
    @PutMapping("setPrivate/{postId}/{isPublic}")
    public Result<?> setPrivate(@PathVariable String postId, @PathVariable Integer isPublic) {
        Post post = new Post();
        post.setIsPublic(isPublic == 1 ? 0 : 1);
        post.setPostId(postId);
        int i = postMapper.updateById(post);
        if (i > 0) {
            return Result.success("设置成功");
        }
        return Result.fail("设置失败");
    }

    // TODO 下架帖子
    @PutMapping("changeStatusPost")
    public Result<?> deletePost(String uid, String sendUid, String title, int isPublic,
                                String postId) {
        if (isPublic == 0) {
            boolean b = postMapper.changePostStatus(1, postId);
            if (b) {
                // 通知用户消息
                String content = "您的帖子[" + title + "]涉嫌违规,已被管理员下架";
                messageMapper.add(uid, sendUid, content, createTime.getTime());
                return Result.success("帖子已下架");
            }
            return Result.fail("帖子下架失败");
        }
        // 进行上架
        boolean b = postMapper.changePostStatus(0, postId);
        if (b) {
            return Result.success("帖子已上架");
        }
        return Result.fail("帖子上架失败");
    }

    // 获取标签
    @GetMapping("getLabel")
    public Result<List<String>> getLabel() {
        List<String> list = postMapper.getLabel();
        // 数组去重
        Set<String> set = new HashSet<>(list);
        list = new ArrayList<>(set);
        // 返回结果
        return Result.success(list);
    }
}
